// Copyright 2025 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package colexec

import (
	"sync"

	"github.com/matrixorigin/matrixone/pkg/container/types"
	"github.com/matrixorigin/matrixone/pkg/objectio"
)

const (
	TxnWorkspaceUnCommitType = 1
)

var (
	// TxnWorkspaceSegment includes a dedicated header which indicates it is a workspace segment.
	TxnWorkspaceSegment = types.Segmentid([16]byte{
		0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0xFF,
	})
)

type CnSegmentMap struct {
	sync.Mutex
	// tag whether a segment is generated by this txn
	mp map[objectio.Segmentid]int32
}

func IsDeletionOnTxnUnCommit(
	segmentMap map[string]int32,
	segId *types.Segmentid,
) bool {
	// raw row id generated by txn.
	// WriteBatch()
	if segId.EQ(&TxnWorkspaceSegment) {
		return true
	}

	// check if it is a persisted segment generated by a workspace.
	if segmentMap != nil {
		return segmentMap[string(segId[:])] == TxnWorkspaceUnCommitType
	} else {
		ss := Get()
		if ss == nil {
			return false
		}

		return ss.GetCnSegmentType(segId) == TxnWorkspaceUnCommitType
	}
}

// IsDeletionOnTxnUnCommitPersisted check if the segId
// is an UnCommit and flushed segment in the workspace.
// if the input map is nil, this check will be done by the colexec.Get.
func IsDeletionOnTxnUnCommitPersisted(
	segmentMap map[string]int32,
	segId *types.Segmentid,
) bool {
	if IsDeletionOnTxnUnCommit(segmentMap, segId) {
		return !segId.EQ(&TxnWorkspaceSegment)
	}
	return false
}

// IsDeletionOnTxnUnCommitInMem check if the segId
// is an UnCommit inmem segment in the workspace.
// if the input map is nil, this check will be done by the colexec.Get.
func IsDeletionOnTxnUnCommitInMem(
	segmentMap map[string]int32,
	segId *types.Segmentid,
) bool {
	if IsDeletionOnTxnUnCommit(segmentMap, segId) {
		return segId.EQ(&TxnWorkspaceSegment)
	}
	return false
}

func RecordTxnUnCommitSegment(segId *types.Segmentid) {
	Get().PutCnSegment(segId, TxnWorkspaceUnCommitType)
}
